package core;

import java.util.Hashtable;

import javax.jms.JMSException;
import javax.jms.Queue;
import javax.jms.QueueConnection;
import javax.jms.QueueConnectionFactory;
import javax.jms.QueueSender;
import javax.jms.QueueSession;
import javax.jms.Session;
import javax.jms.TextMessage;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;

public class Sender {
	
	//private IMessageWriter writer;
	private QueueSender queueSender;
	private QueueSession queueSession;
	//private Hashtable<String, Sender> servidores = new Hashtable<String, Sender>();
	
	public Sender() {
	}
	
	public void inicia(String endereco, String canal) {
		try {
			// criando um contexto JNDI
			Hashtable<String, String> properties = new Hashtable<String, String>();
			properties.put(Context.INITIAL_CONTEXT_FACTORY,"org.exolab.jms.jndi.InitialContextFactory");
			properties.put(Context.PROVIDER_URL, "tcp://" + endereco + "/");
			Context context = new InitialContext(properties);
			
			// recebendo a queue connection factory
			QueueConnectionFactory queueConnectionFactory = (QueueConnectionFactory)context.lookup("JmsQueueConnectionFactory");
			
			// criando uma conexão queue
			QueueConnection queueConnection = queueConnectionFactory.createQueueConnection();
			
			// criando uma sessão queue
			queueSession = queueConnection.createQueueSession(false,Session.AUTO_ACKNOWLEDGE);
			
			// retrieve queue
			Queue queue = (Queue)context.lookup(canal);
			
			// create a queue sender and associate to the retrieved queue
			queueSender = queueSession.createSender(queue);
			
		}
		catch (NamingException e) {
			e.printStackTrace();
		}
		catch (JMSException e) {
			e.printStackTrace();
		}
	}
	
	// Método para enviar mensagens em um determinado canal
	public void sendMessage(String message) {
		try {
			TextMessage textMessage = this.queueSession.createTextMessage(message);
			this.queueSender.send(textMessage);
			
		} catch (JMSException e) {
			e.printStackTrace();
		}
		
	}
	
		/*
		// clean up
		send.queueSender.close();
		send.queueSession.close();
		send.queueConnection.close();
		*/
	
}
